import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/list_empty_widget.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/pages/site/site_device_manager/widgets/tab_item_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/alarm_util.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/navigate_utils.dart';

/**
 *
 * @Description TODO
 * @Author liuer
 * @CreateTime 2024年04月01日 09:28
 */
class SiteDeviceTabview extends StatefulWidget {
  final int siteId;
  final String subSystemId;

  const SiteDeviceTabview(this.siteId, this.subSystemId, {super.key});

  @override
  State<SiteDeviceTabview> createState() => _SiteDeviceTabviewState();
}

class _SiteDeviceTabviewState extends State<SiteDeviceTabview> {
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  DeviceServices services = Get.put(DeviceServices());
  List<dynamic> deviceList = [];
  int currentPage = 1;
  int pageSize = 10;
  bool isLoading = false; //是否请求过数据,如果请求且为空则显示空
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    Log.d('build=======' + widget.subSystemId);
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      controller: refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      header: ListTips.classicHeader,
      footer: ListTips.generateClassicFooter,
      child: deviceList.isEmpty && isLoading
          ? ListEmptyWidget(topPosition: 82)
          : ListView.builder(
              padding: EdgeInsets.zero,
              itemBuilder: (BuildContext context, int index) {
                return TabViewItemWidget(
                    deviceList[index], widget.subSystemId.isEmpty,
                    onItemTaped: (model) {
                  AlarmUtil.fromModule = AlarmFromWhereType.device.value;
                  Log.d(
                      "==== 站点内Tab设备管理模块进入设备模块，值为 ${model.connectStatus} ====");

                  NavigateUtils.toDeviceDetail(
                    model.deviceId ?? -1,
                    model.productType ?? -1,
                    model.deviceName ?? '',
                    ConnectStatusType.on,
                    deviceTree: model,
                    // model.connectStatus != null?$enumDecodeNullable(
                    //   $ConnectStatusTypeEnumMap, model.connectStatus)!:ConnectStatusType.on,
                    productId: model.productId,
                  );
                });
              },
              itemCount: deviceList.length,
            ),
    );
  }

  ///刷新
  void _onRefresh() async {
    currentPage = 1;
    _getDeviceList();
  }

  ///加载更多
  void _onLoading() async {
    currentPage++;
    _getDeviceList();
  }

  _getDeviceList() async {
    var params = {
      'current': currentPage,
      'pageSize': pageSize,
      'siteIds': widget.siteId ?? '',
    };
    if (widget.subSystemId.isNotEmpty) {
      params['classType'] = widget.subSystemId;
    }
    Log.d('params===' + params.toString());
    if (!isLoading) showLoading(toast: ResKey.loading.tr);
    var result = await services.getSiteDeviceList(
      params,
      onError: (p0) {
        refreshController.loadComplete();
        refreshController.refreshCompleted();
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        dismissLoading();
        handleException(p0);
        return false;
      },
    );
    dismissLoading();
    isLoading = true;
    Log.d('result==' + result['list'].toString());
    if (result != null) {
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      setState(() {
        if (currentPage == 1) {
          deviceList.clear();
        }
        deviceList.addAll(result['list'] ?? []);
        if (deviceList.length >= (result['total'] ?? 0)) {
          refreshController.loadNoData();
        }
      });
    }
  }
}
